package com.danielececi.myexpenses;

import java.text.ParseException;
import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.danielececi.constants.IConstants;
import com.danielececi.database.DatabaseHelper;
import com.danielececi.model.Spesa;
import com.danielececi.utils.Utility;

public class GridActivity extends FragmentActivity {

	private DatabaseHelper dbHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_grid);
		
		try {
			this.aggiornaDataTableSpese();
		} catch (ParseException e) {
			Log.e(IConstants.LOG_GRID, e.getMessage());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.grid, menu);
		return true;
	}

	/**
	 * Aggiunge alla riga indicata una colonna con il testo, colore e background desiderati
	 * @param testoColonna
	 * @param riga
	 */
	private void addColumnToRow(TableRow riga, String testoColonna, int textColorID, int drawableId){
		this.addColumnToRow(riga, testoColonna, textColorID , drawableId, -1, View.VISIBLE);
	}
	
	/**
	 * Aggiunge alla riga indicata una colonna con il testo, colore, background e width desiderati
	 * @param riga
	 * @param testoColonna
	 * @param textColorID
	 * @param drawableId
	 * @param widthPx
	 */
	private void addColumnToRow(TableRow riga, String testoColonna, int textColorID , int drawableId, int widthPx){
		this.addColumnToRow(riga, testoColonna, textColorID , drawableId, widthPx, View.VISIBLE);
	}
	
	/**
	 * Aggiunge alla riga indicata una colonna con il testo, colore, background, width e visibility desiderati
	 * @param testoColonna
	 * @param riga
	 * @param widthPx
	 * @param drawableId
	 */
	@SuppressWarnings("deprecation")
	private void addColumnToRow(TableRow riga, String testoColonna, int textColorID , int drawableId, int widthPx, int visibility){
		TextView nuovaColonna = new TextView(getApplicationContext());
		nuovaColonna.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
		nuovaColonna.setTextColor(this.getResources().getColor(textColorID));
		nuovaColonna.setText(testoColonna);
		nuovaColonna.setVisibility(View.VISIBLE);
		if(visibility != -1){
			nuovaColonna.setVisibility(visibility);
		}

		/*final Spannable clientsDebit= new SpannableString(testoColonna);
		clientsDebit.setSpan(new BackgroundColorSpan(this.getResources().getColor(R.color.green)), 0, clientsDebit.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		nuovaColonna.setText(clientsDebit);*/
		 
		//nuovaColonna.setGravity(Gravity.CENTER);
		if(drawableId != -1){
			nuovaColonna.setBackgroundDrawable(this.getResources().getDrawable(drawableId));			
		}
		nuovaColonna.setPadding(5, 3, 5, 3);
		if(widthPx != -1){
			nuovaColonna.setWidth(widthPx);
		}
		riga.addView(nuovaColonna);//Aggiungo la colonna alla riga
	}
	
	/**
	 * Recupera la lista delle spese dal DB e popola la relativa DataTable
	 * @throws ParseException 
	 */
	@SuppressWarnings("deprecation")
	public void aggiornaDataTableSpese() throws ParseException{
		//Recupero le spese dal DB
		this.dbHelper = new DatabaseHelper(this);
		ArrayList<Spesa> listaSpese = this.dbHelper.getListaSpese();
		
		TableLayout dataTable = (TableLayout)findViewById(R.id.dataTableSpese);
	    dataTable.removeAllViews();
	    
	    //Creo la riga con gli header delle colonne
    	TableRow rigaHeader = new TableRow(getApplicationContext());
    	rigaHeader.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    	
    	//Data
    	this.addColumnToRow(rigaHeader, this.getResources().getString(R.string.header_data), R.color.green, R.drawable.header_shape);
    	
        //Categoria
    	this.addColumnToRow(rigaHeader, this.getResources().getString(R.string.header_categoria), R.color.green, R.drawable.header_shape);
    	
        //Importo
    	this.addColumnToRow(rigaHeader, this.getResources().getString(R.string.header_importo), R.color.green, R.drawable.header_shape);
    	
        //Note
    	this.addColumnToRow(rigaHeader, this.getResources().getString(R.string.header_note), R.color.green, R.drawable.header_shape);
    	
    	//Id
    	this.addColumnToRow(rigaHeader, this.getResources().getString(R.string.header_id), R.color.green, R.drawable.header_shape, -1, View.GONE);
    	    	
        dataTable.addView(rigaHeader);//Aggiungo la riga alla tabella
        
        //Scorro la lista delle spese e popolo la DataTable
	    for (int i=0; i<listaSpese.size(); i++) {
			
	    	Spesa spesa = listaSpese.get(i);
	    	
	    	//Creo una nuova riga
	    	TableRow riga = new TableRow(getApplicationContext());
	        riga.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	        
	        //Sfondo delle righe alternato
	        if(i % 2 == 0){
	        	riga.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.rpari_shape));
	        }
	        else{	        	
	        	riga.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.rdispari_shape));
	        }
	        //Sul click prolungato posso cancellare la spesa dal DB
	        riga.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {					
					showDialogCancellaSpesa(v);
					return false;
				}
			});
	        
	        //Creo le colonne
	        
	        //DATA
	        String dataSpesa = Utility.dateToString(spesa.getData(), IConstants.FORMATO_DATA_SPESE);
	        this.addColumnToRow(riga, dataSpesa, R.color.black, -1);
	        
	        //CATEGORIA
	        String categoriaSpesa = spesa.getCategoriaAppartenenza();
	        this.addColumnToRow(riga, categoriaSpesa, R.color.black, -1, 0);
	        
	        //IMPORTO
	        String importoSpesa = Utility.formattaImporto(spesa.getImporto());
	        this.addColumnToRow(riga, importoSpesa, R.color.black, -1);
            
	        //NOTE
	        String noteSpesa = spesa.getNote();
	        this.addColumnToRow(riga, noteSpesa, R.color.black, -1, 0);
	        
	        //ID
	        String idSpesa = String.valueOf(spesa.getId());
	        this.addColumnToRow(riga, idSpesa, R.color.black, -1, -1, View.GONE);
	        
	        dataTable.addView(riga);//Aggiungo la riga alla tabella
		}	    
	}
	
	private void showDialogCancellaSpesa(View v){
		
		//Recupero la riga cliccata
		TableRow rigaCliccata = (TableRow) v;
				
		//Creo un Bundle per passare i dati al dialog
		Bundle datiSpesaSelezionata = new Bundle();
			
		//ID
		TextView colonnaId = (TextView) rigaCliccata.getChildAt(IConstants.COLONNA_ID);
		String id = colonnaId.getText().toString();
		datiSpesaSelezionata.putString(IConstants.KEY_ID, id);
		
		//DATA
		TextView colonnaData = (TextView) rigaCliccata.getChildAt(IConstants.COLONNA_DATA);
		String data = colonnaData.getText().toString();
		datiSpesaSelezionata.putString(IConstants.KEY_DATA, data);
		
		//CATEGORIA APPARTENENZA
		TextView colonnaCategoriaAppartenenza = (TextView) rigaCliccata.getChildAt(IConstants.COLONNA_CATEGORIA_APPARTENENZA);
		String categoriaAppartenenza = colonnaCategoriaAppartenenza.getText().toString();
		datiSpesaSelezionata.putString(IConstants.KEY_CATEGORIA_APPARTENENZA, categoriaAppartenenza);
		
		//IMPORTO
		TextView colonnaImporto = (TextView) rigaCliccata.getChildAt(IConstants.COLONNA_IMPORTO);
		String importo = colonnaImporto.getText().toString();
		datiSpesaSelezionata.putString(IConstants.KEY_IMPORTO, importo);
		
		//NOTE
		TextView colonnaNote = (TextView) rigaCliccata.getChildAt(IConstants.COLONNA_NOTE);
		String note = colonnaNote.getText().toString();
		datiSpesaSelezionata.putString(IConstants.KEY_NOTE, note);
		
		
		DialogCancellaSpesa dialogDelete = new DialogCancellaSpesa();
		dialogDelete.setArguments(datiSpesaSelezionata);
		
		dialogDelete.show(getSupportFragmentManager(), "DialogCancellaSpesa");
	}
	
	public DatabaseHelper getDatabaseHelper(){
		return this.dbHelper;
	}
}
